package com.hmdp.interceptor;

import cn.hutool.core.bean.BeanUtil;
import com.hmdp.common.Constants;
import com.hmdp.common.HostHolder;
import com.hmdp.dto.UserDTO;
import com.hmdp.utils.RedisKeyUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Auther: 公众号/B站：是叶十三
 * @Date: 2022/11/9
 * @Description: com.hmdp.interceptor
 * @version: 1.0
 */
@Component
public class RefreshTokenInterceptor implements HandlerInterceptor, Constants {
    private RedisTemplate redisTemplate;

    public RefreshTokenInterceptor(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }


    // 废弃
/*    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        // 1、获取session
        HttpSession session = request.getSession();
        // 2、从session中获取用户信息
        UserDTO user = (UserDTO)session.getAttribute("user");
        // 3、判断用户是否已存在（已存在说明该用户已经登录了）
        //  3.1 不存在 直接拦截
        if (user == null){
            // 未授权用户无法发送该请求
            response.setStatus(401);
            return false;
        }
        // 3.2 存在，存入UserHoder中，并且放行
        HostHolder.saveUser(user);
        return true;
    }*/

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1、从请求头中获取到token
        String token = request.getHeader("authorization");
        if (token == null || token.equals("")){
            return true;
        }
        //2、基于token去redis中拿用户信息
        String userInfoKey = RedisKeyUtils.getUserInfoKey(token);
        Map<Object, Object> userInfoMap = redisTemplate.opsForHash().entries(userInfoKey);
        //3、判断用户是否存在
        // 3.1 不存在，直接放行
        if (userInfoMap.isEmpty()){
            return true;
        }
        // 3.2 存在，将用户信息存入ThreadLocal中
        UserDTO userDTO = BeanUtil.fillBeanWithMap(userInfoMap, new UserDTO(), false);
        HostHolder.saveUser(userDTO);
        // 3.2 刷新token(用户信息)的有效期
        redisTemplate.expire(userInfoKey, LOGIN_TOKEN_TTL, TimeUnit.MINUTES);
        //4、放行
        return true;
    }

    @Override
    public void afterCompletion(
            HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        // 清空
        HostHolder.removeUser();
    }

}
